package com.kingschan.jeasytag.core.format.impl;

import java.beans.PropertyDescriptor;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import javax.servlet.jsp.PageContext;
import org.apache.log4j.Logger;
import com.kingschan.jeasytag.core.annotations.tag.*;
import com.kingschan.jeasytag.core.format.JeasyTagFormat;
import com.kingschan.jeasytag.core.parse.properties.ParseFactory;
import com.kingschan.jeasytag.core.validation.properties.ValidationFactory;
import com.kingschan.jeasytag.tag.RootTag;
import com.kingschan.util.bean.BeanUtil;
/**
 * format html
 * @author kingschan
 *date:2013-7-11
 */
public class HTMLFormatImpl implements JeasyTagFormat {
	
	private static Logger log = Logger.getLogger(HTMLFormatImpl.class);
	
	String HTML="<${tag} ${class} ${common} data-options=\"${data}\">";
	@Override
	public String format(RootTag tag, PageContext context) throws Exception {
		// NO .1 get all field contrain super class of field
		Field[] fields =BeanUtil.getAllFields(tag);
		//NO 2. get tag Annotation
		TagMetaData sp=tag.getClass().getAnnotation(TagMetaData.class);
		//Classification by Annotation length
		StringBuffer common = new StringBuffer();
		StringBuffer data = new StringBuffer();
		PropertyDescriptor p ;
		for (int i = 0; i < fields.length; i++) {
			Field f =fields[i];
			Annotation[] as	=f.getDeclaredAnnotations();
			if (null!=as&&as.length>0) {
				p= new PropertyDescriptor(f.getName(), tag.getClass());
				Object value =p.getReadMethod().invoke(tag);				
				if(null==value||"".equals(value.toString())){continue;}				
				//first validation it
				ValidationFactory.getValidation(HTMLFormatImpl.returnAkey(as)).validation(f, value);
				if (as.length>1) {
					//>1 means it is common properties
					common.append(f.getName()).append("=\"").append(value.toString()).append("\" ");
				}else{
					//eqalus 1 means it is data properties					
					data.append(ParseFactory.getParse(HTMLFormatImpl.returnAkey(as)).parse(f, value)).append(",");
				}				
				
			}
		}
		String final_html=HTML.replace("${tag}",sp.tag())
		.replace("${class}", "".equals(sp.CssClass())?"":"class=\""+sp.CssClass()+"\"")
		.replace("${common}", common.toString())
		.replace("${data}", data.toString().replaceAll("[,]{1}$+", ""));
		log.debug("final: "+final_html);
		return final_html;
	}
	
	/**
	 * get parse key
	 * @param as
	 * @return
	 */
	public static String returnAkey(Annotation[] as){
		String key =null;
		for (Annotation annotation : as) {
			if (annotation instanceof PropertyField) {
				continue;
			}
			key=annotation.annotationType().getSimpleName();
			//System.out.println(annotation.annotationType().getSimpleName());
		}
		return key;
	}

}
